package com.beordie.version_2.aop.aspect;

import com.beordie.version_2.aop.config.BODJoinPoint;

import java.lang.reflect.Method;

/**
 * @Description
 * @Date 2022/2/22 17:08
 * @Created 30500
 */
public class BODAbstractAspectJAdvice implements BODAdvice{
    /**
     * 织入对象
     */
    private Object aspect;
    /**
     * 增强方法
     */
    private Method adviceMethod;
    /**
     * 异常名称
     */
    private String throwName;

    public BODAbstractAspectJAdvice(Object aspect, Method adviceMethod) {
        this.aspect = aspect;
        this.adviceMethod = adviceMethod;
    }

    public void setThrowName(String throwName) {
        this.throwName = throwName;
    }

    /**
     * 负责对参数的处理执行
     */
    protected Object invokeAdviceMethod(BODJoinPoint joinPoint, Object returnValue, Throwable ex)
            throws Throwable {
        Class<?> [] paramTypes = this.adviceMethod.getParameterTypes();
        if(null == paramTypes || paramTypes.length == 0){
            return this.adviceMethod.invoke(aspect);
        }else {
            Object[] args = new Object[paramTypes.length];
            for (int i = 0; i < paramTypes.length; i++) {
                if (paramTypes[i] == BODJoinPoint.class) {
                    args[i] = joinPoint;
                } else if (paramTypes[i] == Throwable.class) {
                    args[i] = ex;
                } else if (paramTypes[i] == Object.class) {
                    args[i] = returnValue;
                }
            }
            return this.adviceMethod.invoke(aspect, args);
        }
    }
}
